<?php

define( "DATABASE_SERVER", "db1374.1and1.fr" );
define( "DATABASE_USERNAME", "dbo237854838" );
define( "DATABASE_PASSWORD", "w6tG6ATf" );
define( "DATABASE_NAME", "db237854838" );
define( "TABLE_PLAYERS", "mmmad_players");
define( "TABLE_CRISIS", "mmmad_crisis");
define( "TABLE_SESSION", "mmmad_gamesession");

define( "SCORE_STALEMATE", 3);
define( "SCORE_WIN", 10);

//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);

mysql_select_db( DATABASE_NAME );

//Carrousel based on GET variable to decide the action to carry out (one of the available functions)
	//TODO: move to POST when final
switch ($_POST["task"])
{
	case "add_player":
		addPlayer($_POST["name"]);
		break;
	case "update_player_list":
		updatePlayerList();
		break;
	case "update_status":
		updatePlayerStatus($_POST["playerID"]);
		break;
	case "add_crisis":
		addCrisis($_POST["playerID"]);
		break;
	case "respond":
		respondToCrisis ($_POST["crisisID"], $_POST["responseCode"], $_POST["playerID"]);
		break;
	case "update_crisis":
		updateCrisisStatus($_POST["crisisID"]);
		break;
	case "report_idle_opponent":
		setIdle($_POST["idlePlayerID"],$_POST["crisisID"]);
	case "report_active_player":
		unsetIdle($_POST["playerID"]);
	default:
		echo ('default');
		break;
}



// Quote variable to make safe 
function quote_smart($value)
{
	 // Stripslashes
	 if (get_magic_quotes_gpc()) {
	 $value = stripslashes($value);
	 }
	 // Quote if not integer
	 if (!is_numeric($value)) {
	 $value = "'" . mysql_real_escape_string($value) . "'";
	 }
	 return $value;
}

function lockTable ($table)
{
	$lockQuery = sprintf ("LOCK TABLES %s WRITE", $table);
	mysql_query($lockquery);
}

function unlockTables()
{
	$unlockQuery = "UNLOCK TABLES";
	mysql_query($unlockquery);
}



// Add a player into the TABLE_PLAYERS table  
function addPlayer($name)
{
	lockTable(TABLE_PLAYERS);
	
	$addQuery = sprintf("INSERT INTO %s (name) VALUES (%s)", TABLE_PLAYERS, quote_smart($_POST['name']));
	//echo ($addQuery);
	$Result = mysql_query($addQuery);

	$getPlayerIDQuery = sprintf("SELECT * FROM %s WHERE (name = '%s') ORDER BY id DESC",TABLE_PLAYERS, $name);
	
	//echo ($getPlayerIDQuery);
	$Result = mysql_query($getPlayerIDQuery);
	unlockTables();
	$row = mysql_fetch_assoc($Result);
	$Return = "<playerID>".$row['id']."</playerID><playerName>".$row['name']."</playerName>";
	
	mysql_free_result($Result);
	print ($Return.updateSessionStatus());
}

function updateSessionStatus()
{
	$getSessionIDQuery = sprintf("SELECT (id) FROM %s", TABLE_SESSION);
	$Result = mysql_query($getSessionIDQuery);
	$row = mysql_fetch_assoc($Result);
	return ("<sessionID>".$row['id']."</sessionID>");
}

// Update the player list and send it to the client
function updatePlayerList()
{
	$updateQuery = sprintf("SELECT name, score FROM %s WHERE idle < 2", TABLE_PLAYERS);

	$Result = mysql_query($updateQuery);

	$Return = "<players>";

	 while ( $Player = mysql_fetch_assoc($Result) )
		{
			$Return .="<player><name>".$Player['name']."</name><score>".$Player['score']."</score></player>";
		} 

	$Return .= "</players>";
	mysql_free_result($Result);
	print ($Return.updateSessionStatus());
}

// Update the player's status (in a crisis/not in a crisis) and warn the client (send the crisis ID)
function updatePlayerStatus($playerID)
{
	$updateQuery = sprintf("SELECT current_crisis_id, score FROM %s WHERE id = '%s'", TABLE_PLAYERS, $playerID);
	
	$Result = mysql_query($updateQuery);
	
	//process result to see wether the player is in a crisis or not
	//do I need to go fetch the crisis if the player is in one or do it in a separate function?
	
	$Response = mysql_fetch_object($Result);
	
	$Return = "<currentCrisis>".$Response->current_crisis_id."</currentCrisis><score>".$Response->score."</score>";
	
	mysql_free_result ($Result);
	
	print ($Return.updateSessionStatus());
	
}

// Create a new crisis, update the player's current crisis fields and send the crisis ID
function addCrisis ($initiatingPlayerID)
{
	lockTable (TABLE_PLAYERS);
	lockTable (TABLE_CRISIS);
	
	//Find a player currently not in a crisis, different from $initiatingPlayerID and idle=0
	$findAvailablePlayer = sprintf("SELECT id FROM %s WHERE  (current_crisis_id = 0) AND (id != %s) AND (idle = 0) ORDER BY RAND() LIMIT 1", TABLE_PLAYERS, $initiatingPlayerID);
	
	echo ("Available player query :".$findAvailablePlayer."\n");
	
	$Result = mysql_query($findAvailablePlayer);
	$row = mysql_fetch_assoc($Result);
	if ($row['id'] != null) //available player found
	{
		$secondPlayerID = $row['id']; 
		//mysql_free_result($Result);
		//echo ("available Player ID: ".$secondPlayerID);
		//Create a crisis entry in TABLE_CRISIS
		
		$insertNewCrisis = sprintf("INSERT INTO %s (first_player_id, second_player_id) VALUES (%s, %s)", TABLE_CRISIS, $initiatingPlayerID, $secondPlayerID);
		mysql_query($insertNewCrisis);
		//echo ("Insert new crisis query :".$insertNewCrisis."\n");
		
		//update both our "currentcrisis" fields
		$getNewCrisisID = sprintf("SELECT id FROM %s WHERE (first_player_id = %s) AND (second_player_id = %s)", TABLE_CRISIS, $initiatingPlayerID, $secondPlayerID);
		//echo ("get new crisis ID :".$getNewCrisisID."\n");
		$Result = mysql_query($getNewCrisisID);
		
		$row = mysql_fetch_assoc($Result);
		$newCrisisID = $row["id"];
		//echo ("new crisis ID :".$newCrisisID."\n");
		$updatePlayersNewCrisis = sprintf("UPDATE %s SET current_crisis_id=%s WHERE (id=%s) OR (id=%s)", TABLE_PLAYERS, $newCrisisID, $initiatingPlayerID, $secondPlayerID);
		//echo ("update players new crisis ID :".$updatePlayersNewCrisis."\n");
		mysql_query ($updatePlayersNewCrisis);
		
		//return number of the new crisis to client
		
	}
	/* else
	{
	print ("no crisis created");
	} */
	unlockTables();
	
	updatePlayerStatus($initiatingPlayerID);
	
}

function setIdle($idlePlayerID, $crisisID)
{
 //function called by a player whose crisis terminated without reply from opponent
 $setIdleQuery = sprintf("UPDATE %s SET idle = idle + 1 WHERE id = %s", TABLE_PLAYERS, $idlePlayerID);
 mysql_query($setIdleQuery);
 
 respondToCrisis($crisisID, 1, $idlePlayerID);
}

function unsetIdle($playerID)
{
 //called by a function that guarantees the player is not idle anymore
 $unsetIdleQuery = sprintf("UPDATE %s SET idle = 0 WHERE id = %s", TABLE_PLAYERS, $playerID);
 mysql_query($unsetIdleQuery);
}

// Record the response to a crisis and return the outcome code
function respondToCrisis ($crisisID, $responseCode, $playerID)
{
	lockTable(TABLE_CRISIS);
	
	//get crisis we're responding to from TABLE_CRISIS
	$getCrisisQuery = sprintf("SELECT * FROM %s WHERE (id = '%s')", TABLE_CRISIS, $crisisID);
	$Result = mysql_query($getCrisisQuery);
	$row = mysql_fetch_object($Result);
	mysql_free_result ($Result);
	
	//extract respondent and opponent's ids
	if ($row->first_player_id == $playerID)
		$opponentID = $row->second_player_id;
	else
		$opponentID = $row->first_player_id;
	
	//see if the other player has already responded to it
	$outcome = $row->outcome + $responseCode;
	
	$updateOutcomeQuery = sprintf("UPDATE %s SET outcome='%s' WHERE (id='%s')", TABLE_CRISIS, $outcome, $row->id);
	mysql_query ($updateOutcomeQuery);
	
	unlockTables();
	
	switch ($outcome)
	{
		case 2: //both players have responded "stand down"
			$updatePlayerScoresQuery = sprintf("UPDATE %s SET score = score + '%s' WHERE (id = '%s') OR (id = '%s')", TABLE_PLAYERS, SCORE_STALEMATE, $playerID, $opponentID);
			mysql_query ($updatePlayerScoresQuery);
			clearPlayerCrisis($playerID, $opponentID);
			break;
		case 4: //one player escalated and the other stood down
			if ($responseCode == 1)
			{
			$updatePlayerScoresQuery = sprintf("UPDATE %s SET score = score + '%s' WHERE (id = '%s')", TABLE_PLAYERS, SCORE_WIN, $opponentID);
			mysql_query ($updatePlayerScoresQuery);
			}
			else //responseCode == 3
			{
			$updatePlayerScoresQuery = sprintf("UPDATE %s SET score = score + '%s' WHERE (id = '%s')", TABLE_PLAYERS, SCORE_WIN, $playerID);
			mysql_query ($updatePlayerScoresQuery);
			}
			clearPlayerCrisis($playerID, $opponentID);
			break;
		case 6: //both players escalated: APOCALYPSE
			wipeOutWorld();
		default:
			break;
	}
	
	
	
	//return response code
	//print ("<response>".$outcome."</response>".updateSessionStatus());
	
	
}

function clearPlayerCrisis($firstPlayer, $secondPlayer)
{
	$clearCurrentCrisisQuery = sprintf ("UPDATE %s SET current_crisis_id = 0 WHERE (id = '%s') OR (id = '%s')",TABLE_PLAYERS, $firstPlayer, $secondPlayer);
	mysql_query ($clearCurrentCrisisQuery);
}

function updateCrisisStatus($crisisID)
{
	$updateCrisisStatusQuery = sprintf ("SELECT * FROM %s WHERE id = %s", TABLE_CRISIS, $crisisID);
	$Result = mysql_query($updateCrisisStatusQuery);
	$row = mysql_fetch_object($Result);
	$Return = "<id>".$row->id."</id><outcome>".$row->outcome."</outcome><first_player_id>".$row->first_player_id."</first_player_id><second_player_id>".$row->second_player_id."</second_player_id>";
	
	print ($Return.updateSessionStatus());
}

function wipeOutWorld()
{
	lockTable (TABLE_PLAYERS);
	lockTable (TABLE_CRISIS);
	
	//dump DBs to text
	$getAllPlayersDataQuery = sprintf("SELECT * FROM %s", TABLE_PLAYERS);
	$getAllCrisisDataQuery = sprintf("SELECT * FROM %s", TABLE_CRISIS);
	 
	$result = mysql_query($getAllPlayersDataQuery);
	 
	$body = "<players>\n";
 
	while ( $Player = mysql_fetch_assoc($result))
			{
				$body .="\t<player>\n\t\t<id>".$Player['id']."</id>\n\t\t<idle>".$Player['idle']."</idle>\n\t\t<name>".$Player['name']."</name>\n\t\t<score>".$Player['score']."</score>\n\t</player>\n";
			}

	$body .="</players>\n\n<crises>\n"; //crises is the plural of crisis, look it up

	$result = mysql_query($getAllCrisisDataQuery);

	while ( $Crisis = mysql_fetch_assoc($result))
			{
				$body .="\t<crisis>\n\t\t<id>".$Crisis['id']."</id>\n\t\t<first_player_id>".$Crisis['first_player_id']."</first_player_id>\n\t\t<second_player_id>".$Crisis['second_player_id']."</second_player_id>\n\t\t<outcome>".$Crisis['outcome']."</outcome>\n\t</crisis>\n";
			}
	$body .="</crises>";
	
	mysql_free_result($result);
	
	//send mail
	$to = "balthazar.auger@gmail.com";
	$subject = "MMMAD session report - ".date("d-m-y H:i");
	mail($to, $subject, $body);

	//kill everything
	$wipeOutPlayersQuery = sprintf("TRUNCATE TABLE %s",TABLE_PLAYERS);
	$wipeOutCrisesQuery = sprintf("TRUNCATE TABLE %s",TABLE_CRISIS);
	$changeSessionIDQuery= sprintf("UPDATE %s SET id=id+1",TABLE_SESSION);
	mysql_query($wipeOutPlayersQuery);
	mysql_query($wipeOutCrisesQuery); //well, that was quick...
	mysql_query($changeSessionIDQuery);
	
	unlockTables();
}
?>